#include<string>
#include<algorithm>

using namespace std;
class Solution {
public:
    int characterReplacement(string s, int k) {
        if (s.size() <= 1) return s.size();
        int nums[26];
        memset(nums, 0, 26 * sizeof(int));
        int left = 0, right = 0;
        int maxIndex = 0;
        int maxCount = 0;
        while (right < s.size()) {
            int index = s[right++] - 'A';
            ++nums[index];
            if (nums[index] > maxCount) {
                maxCount = nums[index];
                maxIndex = index;
            }
            if (maxCount + k < (right - left)) {
                int index = s[left++] - 'A';
                --nums[index];
                if (index == maxIndex) {
                    maxCount = 0;
                    for (int i = 0; i < 26; ++i) {
                        if (nums[i] > maxCount) {
                            maxCount = nums[i];
                            maxIndex = i;
                        }
                    }
                }
            }
        }
        return right - left;
    }
};